# Importing Data
BELGIUM <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Saudi Arabia/Belgium.xlsx")

# Checking the Imported Data
View(BELGIUM)
Vehicles
# Creating Time Series Data
BELGIUM_ts <- ts(BELGIUM, start=c(2004,1), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
BELGIUM_ts
sum(is.na(BELGIUM_ts))
library(forecast)
BELGIUM_ts <- tsclean(BELGIUM_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(BELGIUM_ts)
plot(aggregate(BELGIUM_ts,FUN=mean))

# Decomposing
BELGIUM_ts_decomp <- decompose(BELGIUM_ts)
plot(BELGIUM_ts_decomp)

# Testing for Stationarity
acf(BELGIUM_ts, lag.max=20)
pacf(BELGIUM_ts, lag.max=20)

# To see any seasonal effect
boxplot(BELGIUM_ts~cycle(BELGIUM_ts))

# To remove trend effect
BELGIUM_ts_diff <- diff(BELGIUM_ts)
plot(BELGIUM_ts_diff)

# To remove variance effect
BELGIUM_ts_log <- log(BELGIUM_ts)
plot(BELGIUM_ts_log)

# To remove both (Trend and Variance) effects
BELGIUM_ts_both <- diff(log(BELGIUM_ts))
plot(BELGIUM_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(BELGIUM_ts, lag.max=20)
acf(log(BELGIUM_ts), lag.max=20)
acf(diff(BELGIUM_ts), lag.max=20)
acf(diff(log(BELGIUM_ts)), lag.max=20)
pacf(BELGIUM_ts, lag.max=20)
pacf(log(BELGIUM_ts), lag.max=20)
pacf(diff(BELGIUM_ts), lag.max=20)
pacf(diff(log(BELGIUM_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
BELGIUM_ts_model <- auto.arima(BELGIUM_ts)
BELGIUM_ts_model
BELGIUM_ts_model <- auto.arima(BELGIUM_ts, ic="aic", trace = TRUE)
BELGIUM_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(BELGIUM_ts_model$resid)
acf(BELGIUM_ts_model$residuals, main='ACF Residual')
pacf(BELGIUM_ts_model$residuals, main='ACF Residual')
Box.test(BELGIUM_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
BELGIUM_ts_forecast <- forecast (BELGIUM_ts_model, level=c(95), h=258)
plot(BELGIUM_ts_forecast)
BELGIUM_ts_forecast             


write.table(BELGIUM_ts_forecast, file="Belgium_TSA.csv", sep=",")
